<template>
  <div class="withdraw">
    <CustomNavBar :title="t('Withdraw')"> </CustomNavBar>
    <div class="container">
      <div class="headContainer">
        <div class="headContainer-title">{{t('Trading Balance')}}</div>
        <div class="headContainer-value">₹{{ decimalpre(detail.balance || 0) }}</div>
      </div>
      <van-cell :title="t('Select Bank')" is-link :value="selectedBank.name" :arrow-direction="show?'down':'right'" @click="openPopup"/>
      <van-cell :title="t('Bank Account Number')" :value="selectedBank.code" />
      <van-cell :title="t('Withdrawal Handling Fee')" :value="`${systemConfigMap.withdraw_service_fee?.value ?? 0}%`" />
      <div class="card box-show-0">
        <van-field
          :label="t('Enter Amount')"
          :placeholder="t('Enter Amount')"
          v-model="amount"
          type="number"
          maxlength="12"
          input-align="right"
        />
        <div class="feeBalance">{{t('Withdrawal Handling Fee')}}: 0</div>
        <div class="receivedAmount">
          {{t('Amount Received')}}: {{ amount ? `₹${decimalpre(amount)}` : 0 }}
        </div>
      </div>
      <button
        class="btns van-button van-button--primary van-button--normal van-button--block"
        style="
          color: white;
          background: rgb(50, 93, 121);
          border-color: rgb(50, 93, 121);
          width: 100%;
        "
        @click="handleSubmit"
      >
        <div class="van-button__content">
          <span class="van-button__text">{{t('Withdrawal')}}</span>
        </div>
      </button>
      <div class="line"></div>
      <div class="card">
        <div class="title">{{t('Withdrawal Instructions')}}</div>
        <ul class="des">
          <li class="des-item">
            {{t('1. The minimum withdrawal amount is ₹{ value } rupees', {value: decimalpre(systemConfigMap.min_withdraw_amount?.value)})}}
          </li>
          <li class="des-item">
            {{t('2. Withdrawal time: Monday to Friday {start_time} - {end_time}', {start_time: systemConfigMap.withdraw_start_time?.value, end_time: systemConfigMap.withdraw_end_time?.value})}}
          </li>
          <li class="des-item">
           {{t('3. Do not urge your manager within 48 hours after submitting the application. Once you submit the withdrawal, the bank will queue up for you. If you do not receive your withdrawal within 48 hours, please contact your manager for inquiry.')}}
          </li>
          <li class="des-item">
           {{t('4. IFSC should be 11 characters, the fifth character should be "0", not "O". If the bank information you filled in is incorrect, your withdrawal will fail.')}}
          </li>
          <li class="des-item">
            {{t('5. If you have any questions, please contact the organization commissioner.')}}
          </li>
          <li class="des-item">
           {{t('6. Withdrawals are available from {start_time} am to {end_time} pm', {
            start_time: systemConfigMap.withdraw_start_time?.value,
            end_time: systemConfigMap.withdraw_end_time?.value
           })}}
          </li>
        </ul>
      </div>
      <div class="van-overlay" style="z-index: 2005;display:none;"></div>

      <van-popup v-model:show="show" :style="{ padding: '64px' }">
        <div class="lang-container">
          <div class="lang-head">{{t('Select Bank')}}</div>
          <div class="lang-content">
            <div class="lang-item" :class="{'lang-item-active': selectedBank.id === item.id}" v-for="item in bankList" :key="item.id" @click="changeBank(item)">{{ item.name }}</div>
          </div>
        </div>
      </van-popup>
    </div>
  </div>
</template>
<script setup>
import { ref, onBeforeMount, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showSuccessToast, showToast } from 'vant'
import { get, post } from '@/utils/request'
import { decimalpre } from '@/utils/util'
import store from '@/store/index'
import { t } from '@/languages'
const router = useRouter()

const show = ref(false)

const amount = ref('')

const systemConfigMap = computed(() => store.systemConfigMap)

function openPopup() {
  show.value = !show.value
}

function goWithdrawDetail(){
  router.push('/withdrawDetail')
}


const detail = ref(JSON.parse(sessionStorage.getItem('my-info') || '{}'))

async function getUserInfo() {
  try {

    const res = await get(`/api/app/getmyinfo/`, {})

    detail.value = res

    sessionStorage.setItem('my-info', JSON.stringify(res))

  } catch (error) {
    console.log(error)
  }
}

const bankList = ref([])

async function queryList() {
  try {
    const res = await get(`/api/app/banks/`, {})

    console.log(res)

    bankList.value = res

  } catch (error) {
    console.log(error)
  }
}

const selectedBank = ref({})
function changeBank(val) {
  selectedBank.value = val

  show.value = false
}


const loading = ref(false)
async function handleSubmit() {
  if(detail.value.withdraw_permission !== 0) {
    showToast(t('No withdrawal permission'))
    return
  }
  if (!detail.value.balance) {
    return showToast(t('No balance'))
  }

  if (!selectedBank.value.id) {
    return showToast(t('Please select the bank'))
  }

  if (!amount.value) {
    return showToast(t('The amount cannot be empty'))
  } else {
    let msg = ''

    if (amount.value > detail.value.balance) {
      msg = t('Insufficient balance')
    }

    if (amount.value < systemConfigMap.value.min_withdraw_amount?.value) {
      msg = t(`The minimum withdrawal amount shall not be less than {value}`, {value: systemConfigMap.value.min_withdraw_amount.value})
    }

    if (amount.value > systemConfigMap.value.max_withdraw_amount?.value) {
      msg = t(`The maximum withdrawal amount shall not exceed {value}`, {value: systemConfigMap.value.max_withdraw_amount.value})
    }

    if (msg) {
      return showToast(msg)
    }
  }

  loading.value = true

  try {
    const res = await post(`/api/app/withdraw/`, {
      amount: +amount.value,
      bank_id: selectedBank.value.id,
      service_fee: +(systemConfigMap.value.withdraw_service_fee?.value ?? 0)
    })

    showSuccessToast(t('Withdraw success'))

    getUserInfo()

    amount.value = ''

  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

onBeforeMount(() => {
  getUserInfo()
  queryList()
})
</script>
<style lang="scss">
.withdraw {
  height: 100%;
  padding-bottom: 5.33333rem;
  overflow: auto;
}

.withdraw .container {
  padding: 0.26667rem;
  overflow: hidden;
  padding-bottom: 0.8rem;
}

.withdraw .container .headContainer {
  box-shadow: 0 0.10667rem 0.37333rem 0 rgba(0, 0, 0, 0.25);
  padding: 0.66667rem 0.48rem;
  border-radius: 0.21333rem;
}

.withdraw .container .headContainer .headContainer-title {
  font-weight: 700;
  color: #6d6d6d;
  text-align: center;
}

.withdraw .container .headContainer .headContainer-value {
  color: #62f8a2;
  font-size: 0.74667rem;
  font-weight: 600;
  margin-top: 0.13333rem;
  text-align: center;
}

.withdraw .container .card {
  margin-top: 0.26667rem;
  border-radius: 0.26667rem;
}

.withdraw .container .card .title {
  padding: 0.13333rem 0;
  font-size: 0.37333rem;
  color: #fff;
  font-weight: 700;
  margin-top: 0.53333rem;
}

.withdraw .container .card .des .des-item {
  font-size: 0.32rem;
  padding: 0.13333rem 0.53333rem;
}

.withdraw .container .card .feeBalance {
  text-align: right;
  color: #fff;
  font-size: 0.32rem;
  margin-top: 0.4rem;
}

.withdraw .container .card .receivedAmount {
  text-align: right;
  color: #fff;
  font-size: 0.32rem;
  padding-top: 0.13333rem;
}

.withdraw .container .btns {
  margin-top: 0.8rem;
}

.withdraw .container .line {
  margin-top: 1.06667rem;
  padding-bottom: 1.06667rem;
  border-bottom: 0.02667rem solid rgba(0, 0, 0, 0.3);
}

.withdraw .van-popup {
  width: 80%;
  background: #0e1822;
  border-radius: 0.13333rem;
}

.withdraw .van-popup .lang-container {
  padding: 0.8rem;
}

.withdraw .van-popup .lang-container .lang-head {
  text-align: center;
  font-weight: 600;
}

.withdraw .van-popup .lang-container .lang-content {
  max-height: 6.5rem;
  overflow-y: auto;
  margin-top: 0.8rem;
  display: flex;
  flex-direction: column;
  align-content: center;
  align-items: center;
}

.withdraw .van-popup .lang-container .lang-content .lang-item {
  width: 5.06667rem;
  height: 1.33333rem;
  line-height: 1.33333rem;
  text-align: center;
  border-radius: 0.26667rem;
  color: #fff;
  font-weight: 500;
  margin-bottom: 0.26667rem;
  background-color: #235588;
}

.withdraw .van-popup .lang-container .lang-content .lang-item-active {
  background-color: #f8b253;
  color: #000;
}

.withdraw .van-button {
  border-radius: 0.26667rem;
  height: 1.33333rem;
}

.withdraw .van-cell {
  border-radius: 0.16rem;
  padding-right: 0.26667rem;
  margin-top: 0.26667rem;
}

.withdraw .van-cell,
.withdraw .van-field {
  background: #0e1822;
  border: 0.02667rem solid #2b4e5a;
}

.withdraw .van-field__label {
  color: #ccc !important;
  font-size: 0.37333rem;
}

.withdraw .van-cell__title {
  color: #ccc;
  font-size: 0.37333rem;
}

.withdraw .van-cell__value,
.withdraw .van-field__control {
  color: #ccc;
}

.withdraw .van-cell:after {
  border: 0;
}

.withdraw .van-field__control::placeholder {
  color: #a0a0a0;
}

.withdraw .van-field__control--right {
    -webkit-box-pack: end;
    -webkit-justify-content: flex-end;
    justify-content: flex-end;
    text-align: right
}
.withdraw .van-field__label {
    -webkit-box-flex: 0;
    -webkit-flex: none;
    flex: none;
    box-sizing: border-box;
    width: 6.5em;
    margin-right: .32rem;
    color: #646566;
    text-align: left;
    word-wrap: break-word
}
</style>
